package com.yueyang.sojourn.server.controller.order;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.common.consts.Constants;
import com.yueyang.sojourn.server.controller.BaseController;
import com.yueyang.sojourn.server.controller.model.JsonResult;
import com.yueyang.sojourn.server.model.dto.AddOrderRefundDto;
import com.yueyang.sojourn.server.model.enums.OrderStatusEnum;
import com.yueyang.sojourn.server.model.po.*;
import com.yueyang.sojourn.server.model.vo.SojournOrderDetailVo;
import com.yueyang.sojourn.server.model.vo.SojournOrderListVo;
import com.yueyang.sojourn.server.model.vo.SojournOrderTouristVo;
import com.yueyang.sojourn.server.model.vo.SojournOrderVo;
import com.yueyang.sojourn.server.service.attachdetail.AttachDetailService;
import com.yueyang.sojourn.server.service.sojourn.merch.SojournMerchService;
import com.yueyang.sojourn.server.service.sojourn.order.*;
import com.yueyang.sojourn.server.service.sojourn.project.SojournProjectService;
import com.yueyang.uc.model.UcUserV1;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * 订单后台服务
 * @author andy.yang
 * @version v1
 * @summary
 * @Copyright (c) 2019, yueyang Group All Rights Reserved.
 * @since 2020/3/17
 */
@Api(tags = "订单退款单 API")
@RestController
@RequestMapping("/sojourn/order/refund")
@Slf4j
public class SojournOrderRefundController extends BaseController {
    @Autowired
    SojournOrderRefundService refundService;
    @Autowired
    SojournOrderService orderService;
    @Autowired
    SojournOrderMsgService msgService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    /**
     * 发送退款单验证码
     *
     * @param orderId
     * @return
     */
    @ApiImplicitParam(name = "X-Token", paramType = "header", required = true)
    @ApiOperation(value = "发送退款单验证码")
    @PostMapping("/captcha")
    public String sendClinchOrderCaptcha(@ApiParam(value = "订单id") @RequestParam(value = "orderId") Long orderId) {
        UcUserV1 loginUser = getLoginUser();
        msgService.sendRefundCaptcha(loginUser.getPhone(),orderId);
        return loginUser.getPhoneShow() == null ?
                loginUser.getPhone().substring(0,3) + "****" + loginUser.getPhone().substring(7) : loginUser.getPhoneShow();
    }

    /**
     * 创建退款单
     *
     * @param refundDto
     * @return
     */
    @ApiImplicitParam(name = "X-Token", paramType = "header", required = true)
    @ApiOperation(value = "创建退款单")
    @PostMapping("")
    public JsonResult<Long> createOrderRefund(@RequestBody @Validated AddOrderRefundDto refundDto, BindingResult bindingResult) {
        FieldError fieldError = bindingResult.getFieldError();
        if (Objects.nonNull(fieldError)) {
            JAssert.justFailed(fieldError.getDefaultMessage());
        }

        if(refundDto.getThirdRefunded() == null || (refundDto.getThirdRefunded() != 0 && refundDto.getThirdRefunded() != 1)){
            return fail("是否付款标识错误");
        }
        UcUserV1 loginUser = super.getLoginUser();
        SojournOrder order = orderService.findById(refundDto.getOrderId());
        if(order == null){
            return fail("订单不存在");
        }

        if(order.getStatus() != OrderStatusEnum.TO_BE_TRIP.getCode()){
            return fail("订单状态错误，不能退款");
        }

        if(!msgService.verifiRefundCaptcha(loginUser.getPhone(),order.getId(),refundDto.getCaptcha())){
            return fail("验证码输入错误");
        }
        //数据验证
        SojournOrderRefund refundOld = refundService.findByOrderId(refundDto.getOrderId());
        if(refundOld != null){
            return fail("订单退款单已存在");
        }

        SojournOrderRefund refund = new SojournOrderRefund();
        BeanUtils.copyProperties(refundDto,refund);
        refund.setOrderType(order.getType());
        refund.setCreator(loginUser.getId());
        refund.setTotalFee(new BigDecimal(0));
        refundService.add(refund);
        JsonResult rs = ok();
        rs.setData(refund.getId());
        return rs;
    }
}
